<template>
    <div class="widthAll">
        <div style="text-align: right;">
            <el-button @click="down" size="small" style="border: none; margin-right: 45px;"><span
                    class="icon hll-xiazai"
                    style=" font-size: 20px;"></span>
            </el-button>
        </div>
        <div id="main" style="height: 370px;width: 100%;"></div>
    </div>
</template>

<script>

import {EleResize} from "../../../assets/js/resize";
import {getCollapse} from "../../../store/session";
import html2canvas from "html2canvas"
import categoryInfo from "../../../store/categoryInfo";
import bookInfo from "../../../store/bookInfo";
import borrowInfo from "../../../store/borrowInfo";

export default {
    name: 'bar',
    data() {
        return {
            myChart: null,
            div: null,
            categories: ['医学', '计算机科学', '医学', '计算机科学', '医学', '计算机科学', '医学', '计算机科学',],
            borrows: [1, 2, 1, 2, 1, 2, 1, 200],
            books: [4, 9, 4, 9, 4, 9, 4, 9],
            idsBorrow: new Map(), //category_id->borrows
            idsBook: new Map(), //category_id->books
            idsCB: new Map(),// bookId->categoryID
            ids: [] //category所有 id
        }
    },
    // 此时,页面上的元素,已经被渲染完毕了
    mounted() {
        const _this = this;
        _this.div = document.getElementById('main');
        _this.preHandle();
        _this.fetchData(); //获取数据
    },
    methods: {
        fetchData() {
            const _this = this;
            _this.borrows = null;
            categoryInfo.dispatch('queryCategoriesAll').then((rs) => {
                _this.categories = [];
                rs.forEach(function (item) {
                    _this.categories.push(item.name);
                    //初始化map
                    _this.idsBook.set(item.id, 0);
                    _this.idsBorrow.set(item.id, 0);
                    _this.idsBook = new Map(_this.idsBook);
                    _this.idsBorrow = new Map(_this.idsBorrow);
                    _this.ids.push(item.id);
                });
                _this.fetchBooks();
            });
        },
        fetchBooks() {
            const _this = this;
            bookInfo.dispatch('queryAllBooks', {}).then(rs => {
                rs.forEach(function (item) {
                    /*由于borrow只知道book不知道category，所以需要*/
                    _this.idsCB.set(item.id, item.category);
                    _this.idsCB = new Map(_this.idsCB);
                    _this.idsBook.set(item.category, _this.idsBook.get(item.category) + 1);
                    _this.idsBook = new Map(_this.idsBook);
                });

                _this.fetchBorrows();
            })
        },
        fetchBorrows() {
            const _this = this;
            borrowInfo.dispatch('queryAllBorrows').then(rs => {
                rs.forEach(function (item) {
                    let category = _this.idsCB.get(item.bookId); //分类id
                    _this.idsBorrow.set(category, _this.idsBorrow.get(category) + 1);
                    _this.idsBorrow = new Map(_this.idsBorrow);
                })
                _this.merge(); //整合数据
                _this.refresh(); /*绘制表格*/
                _this.afterHandle();
            })
        },
        merge() {
            const _this = this;
            _this.books = [];
            _this.borrows = [];
            _this.ids.forEach(function (item) {
                _this.books.push(_this.idsBook.get(item));
                _this.borrows.push(_this.idsBorrow.get(item));
            });
            _this.refresh(); //绘制图表
        },
        preHandle() {
            if (getCollapse()) /*不这么设置的话，echarts宽度有问题,93相当于去除侧边栏以及周边空白的部分*/
                this.div.style.width = document.body.clientWidth - 93 + 'px';
        },
        afterHandle() {
            const _this = this;
            /*宽度自适应*/
            let listener = function () {
                _this.myChart.resize();
            }
            EleResize.on(_this.div, listener)

            /*改回去*/
            _this.div.style.width = '100%';
        },
        down() {
            /*下载为png图片*/
            html2canvas(document.getElementById("main")).then(function (canvas) {
                var img = canvas
                    .toDataURL("image/png")
                    .replace("image/png", "image/octet-stream");
                // 创建a标签，实现下载
                var creatIMg = document.createElement("a");
                creatIMg.download = "bookChart.png"; // 设置下载的文件名，
                creatIMg.href = img; // 下载url
                document.body.appendChild(creatIMg);
                creatIMg.click();
                creatIMg.remove(); // 下载之后把创建的元素删除
            });
        },
        refresh() {
            const _this = this;
            let echarts = require('echarts');
            _this.myChart = echarts.init(document.getElementById('main'));
            let option = {
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                        type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                    }
                },
                legend: {
                    data: ['借阅', '书籍']
                },
                title: {
                    text: '后台报表',
                    subtext: '各分类借阅数以及书籍数'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                xAxis: {
                    data: _this.categories,
                    axisLabel: {
                        interval: 0,
                        inside: false,
                        textStyle: {
                            color: '#6F7691',
                            fontSize: 15,
                            itemSize: ''
                        }
                    },
                    axisTick: {
                        show: true,
                        alignWithLabel: true,
                    },
                    axisLine: {
                        show: true
                    },
                    z: 10
                },
                yAxis: {
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    },
                    axisLabel: {
                        textStyle: {
                            color: '#999'
                        }
                    }
                },
                dataZoom: [
                    {
                        type: 'inside'
                    }
                ],
                series: [
                    {
                        type: 'bar',
                        name: '借阅',
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1,
                                [ /*渐变式柱形条*/
                                    {offset: 0, color: '#83bff6'},
                                    {offset: 0.5, color: '#188df0'},
                                    {offset: 1, color: '#188df0'}
                                ]
                            )
                        },
                        data: _this.borrows,
                        emphasis: {
                            focus: 'series'
                        },
                    },
                    {
                        name: '书籍',
                        type: 'bar',
                        data: _this.books,
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(
                                0, 0, 0, 1,
                                [
                                    {offset: 0, color: '#A8DB9B'},
                                    {offset: 0.5, color: '#91CC75'},
                                    {offset: 1, color: '#5CBB44'}
                                ]
                            )
                        },
                        emphasis: {
                            focus: 'series'
                        },
                    },

                ],
                animationEasing: 'cubicOut', //elasticOut另一种效果
                animationDuration: function (idx) {
                    // 越往后的数据时长越大
                    return idx * 100;
                },
                animationDelay: function (idx) {
                    // 越往后的数据延迟越大
                    return idx * 100;
                },
                animation: true,
            };

            // Enable data zoom when user click bar.
            const zoomSize = 10;
            _this.myChart.on('click', function (params) {
                _this.myChart.dispatchAction({
                    type: 'dataZoom',
                    startValue: _this.categories[Math.max(params.dataIndex - zoomSize / 2, 0)],
                    endValue: _this.categories[Math.min(params.dataIndex + zoomSize / 2, _this.borrows.length - 1)]
                });
            });
            _this.myChart.clear();
            _this.myChart.setOption(option, true)
        },

    }
}
</script>
